package org.lex.keytool.ui.builder;

import java.awt.Component;
import java.awt.Window;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;

import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JTextField;
import javax.swing.SwingUtilities;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class FileChooserBuilder {
	public static void addHandler(JButton button, JTextField textField, boolean isOpen) {
		button.addActionListener(new FileChooserHandler(textField, isOpen));
		String btext = null;
		if (isOpen) {
			btext = "Open...";
		} else {
			btext = "Save...";
		}
		button.setText(btext);
	}

	private static class FileChooserHandler implements ActionListener {
		private Logger log = LoggerFactory.getLogger(FileChooserHandler.class);
		private final JTextField textField;
		private final boolean isOpen;

		public FileChooserHandler(JTextField textField, boolean isOpen) {
			this.textField = textField;
			this.isOpen = isOpen;
		}

		@Override
		public void actionPerformed(ActionEvent e) {
			JFileChooser fc = new JFileChooser();
			fc.setFileSelectionMode(JFileChooser.FILES_ONLY);
			fc.setMultiSelectionEnabled(false);

			String init = textField.getText().trim();
			if (false == init.isEmpty()) {
				log.info("init dir=" + init);
				fc.setSelectedFile(new File(init));
			}

			int ret = -1;
			Component root = SwingUtilities.getAncestorOfClass(Window.class, textField);
			if (true == isOpen) {
				ret = fc.showOpenDialog(root);
			} else {
				ret = fc.showSaveDialog(root);
			}
			log.debug("FileChooser return value=" + ret);
			if (ret == JFileChooser.APPROVE_OPTION) {
				File file = fc.getSelectedFile();
				log.info("selected file=" + file);
				textField.setText(file.getAbsolutePath());
			}
		}
	}
}
